package com.rbcs.base.currency.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.rbcs.base.model.Currency;
import com.systop.core.ApplicationException;
import com.systop.core.service.BaseGenericsManager;

/**
 * 币种管理Manager
 * @author ShangHua
 */
@Service
@SuppressWarnings({"rawtypes", "unchecked"})
public class CurrencyManager extends BaseGenericsManager<Currency> {
	
  /**
   * 保存外币币种信息
   */
	@Override
	@Transactional
	public void save(Currency currency) {
		if (getDao().exists(currency, "name")) {
			if (StringUtils.isNotEmpty(currency.getName())) {
				throw new ApplicationException("外币币种为【" + currency.getName() + "】的信息已存在。");
			}
		}
		super.save(currency);
	}
  
  /**
   * 查询所有的币种集合
   * @return
   */
	public List<Currency> getCurrencyList() {
    List list = getDao().query("from Currency c order by c.name asc");
    return list;
  }
	
  /**
   * 查询所有的币种(下拉列表使用)
   * @return
   */
	public List getCurrencyInfo() {
    List list = getDao().query("from Currency c");
    if (CollectionUtils.isNotEmpty(list)){
      return toMapArray(list);  
    }
    return list;
  }
  
  /**
   * 查询结果中的List中的Currency对象转换为Map对象.
   * @param List of Currency
   * @return list of map
   */
  private static List<Map> toMapArray(List<Currency> list) {
    List<Map> result = new ArrayList(list.size());
    for (Currency currency : list) {
      Map<String, String> item = new HashMap<String, String>();
      item.put("id", currency.getId().toString());
      item.put("name", currency.getName()); 
      result.add(item);
    }
    return result;
  }
}
